<?php
namespace App\Services;
use CzProject\GitPhp\Git as GIT1;
class GitService
{
    private $filePath;
    private $repo;
    private $projectName;
    public function __construct($projectName) {

        $this->filePath = self::getRootPath($projectName);
        $this->projectName = $projectName;
        $git = new GIT1();
        if (self::isGitProject($projectName)) {
            $this->repo = $git->open($this->filePath);
        }
    }

    /**
     * 获取变动的文件
     * @return array|array[]
     * @throws \CzProject\GitPhp\GitException
     */
    public function getChangedFiles() : array {
        $this->repo->execute('reset','--hard');   // 将服务器的分枝移动到最新
        $lines = $this->repo->execute("whatchanged", "-1");
        $files = [
            'A' => [],  // 新增
            'M' => [],  // 修改
            'R' => [],  // 移动
            "D" => []   // 删除
        ];
        logger($lines);
        foreach ($lines as $line) {
            if (preg_match("/^:/", $line)) {

                $line = trim(mb_substr($line,31));
                $type = mb_substr($line,0,1);
                $line = explode("\t", $line);
                $line = $line[1];
                $files[$type][] = $line;
            }
        }

        return $files;
    }

    /**
     * 创建仓库
     * @throws \CzProject\GitPhp\GitException
     */
    public function createRepository() : void {
        $git = new GIT1();
        $git->init($this->filePath);

        // 修改允许提交
        $configFile = $this->filePath.'/.git/config';
        $updateFile = $this->filePath.'/.git/hooks/post-update';
        unlink($configFile);
        copy(resource_path("template/git.config"), $configFile);    // 覆盖配置文件

        // 更新的钩子目前存在一个问题，复制过来之后权限被改变了，导致无法执行
        copy($updateFile.'.sample', $updateFile);

        $systemPath = str_replace("\\","\\\\", base_path());
        $cmd = "#!/bin/bash\n\r";
        $cmd .= "cd {$systemPath} && php artisan file:monitor ". $this->projectName;
        file_put_contents($updateFile, $cmd);    // 修改钩子文件
        $res = chmod($updateFile, 0777);
        $this->repo = $git->open($this->filePath);
    }

    /**
     * 检查是否存在某GIT项目
     * @param string $name
     * @return bool
     */
    static function isGitProject(string $name) : bool {
        $path = self::getRootPath($name);

        if (!file_exists($path)) {
            return false;
        }

        $git = new GIT1();
        try {
            $git->open($path);
            return true;
        } catch (\Exception $e) {
            return  false;
        }
    }

    static function getRootPath($name) : string {
        return config('git.root') . '/'.$name;
    }
}
